package com.vogue.meeting.common.configuration;

import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.vogue.meeting.common.db.DataSourceEnum;
import com.vogue.meeting.common.db.DynamicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan({"com.vogue.meeting.fluent.mapper", "com.vogue.meeting.common.security.dao"})
public class FluentMybatisConfig {

    // 定义fluent mybatis的MapperFactory
    @Bean
    public MapperFactory mapperFactory() {
        return new MapperFactory();
    }

    /**
     * 数据源
     * */
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master-data-source")
    public DataSource defaultDataSource(){
        return DruidDataSourceBuilder.create().build();
    }
    /**
     * 动态数据源
     * 相关代码{@link DynamicDataSource#DynamicDataSource(DataSource, Map)}
     * */
    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource defaultDataSource) {
        Map<String, DataSource> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceEnum.MASTER.getName(), defaultDataSource);
        return new DynamicDataSource(defaultDataSource, targetDataSources);
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource(defaultDataSource()));

        //ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        // 以下部分根据自己的实际情况配置
        // 如果有mybatis原生文件, 请在这里加载
        //    bean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
        //    /* bean.setMapperLocations(
        //    /*      new ClassPathResource("mapper/xml1.xml"),
        //    /*      new ClassPathResource("mapper/xml2.xml")
        //    /* );
        //    */
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLazyLoadingEnabled(true);
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean;
    }
}
